package manager

import (
	"NovelBook/logic/book"
	"NovelBook/models/db_models"
	"NovelBook/utils/auth"
	"NovelBook/utils/response"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"strings"
)

// CreateBooks 创建书籍
//
//	@Summary		创建书籍
//	@Description	向系统中创建新的书籍内容，书籍可以是多个，必须包含所有描述书籍的字段
//	@Tags			Manager
//	@Accept			json
//	@Produce		json
//	@Security		ApiKeyAuth
//	@Param			Authorization	header		string			true	"`Bearer Token` 使用空格分隔`Bearer`与`Token`"
//	@Param			books			body		[]models.Books	true	"`Books`信息，`required`标识字段必须绑定"
//	@Success		200				{object}	msg.Code1000	"获取成功"
//	@Failure		400				{object}	msg.Code1001	"1.请求参数错误`msg`字段为：`Invalid params` <br> 2.书籍已存在`msg`字段为：`BOOK EXIST`"
//	@Failure		401				{object}	msg.Code1005	"无效的`Token`"
//	@Failure		503				{object}	msg.Code1003	"系统繁忙，请稍后再试"
//	@Router			/manager/books/new [post]
func CreateBooks(c *gin.Context) {
	idAny, exit := c.Get(auth.ManagerIDKey)
	id := idAny.(uint)
	if !exit || id < 0 {
		response.Fail(c, http.StatusUnauthorized, response.CodeTokenInvalid)
		return
	}
	var books []db_models.Books
	err := c.ShouldBindJSON(&books)
	if err != nil {
		response.Fail(c, http.StatusBadRequest, response.CodeParamsInvalid)
		log.Println("bind err : ", err)
		return
	}
	err = book.CreateBooks(books)
	if err != nil {
		log.Println(err)
		split := strings.Split(err.Error(), " ")
		if split[1] == "1062" {
			response.FailWithMsg(c, http.StatusBadRequest, response.CodeParamsInvalid, "BOOK EXIST")
			return
		}
		response.FailWithMsg(c, http.StatusServiceUnavailable, response.CodeSystemBusy, "database insert error")
		return
	}
	response.Success(c, nil)
}
